package com.examplemartin.jpademo.service;


import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.dao.Dynamic_RepoInfoDao;
import com.examplemartin.jpademo.dao.StockDao;
import com.examplemartin.jpademo.pojo.po.good.GoodPO;
import com.examplemartin.jpademo.pojo.po.stock.RepoInfoPO;
import com.examplemartin.jpademo.pojo.po.stock.StockPO;
import com.examplemartin.jpademo.util.EntityCheckUtil;
import com.examplemartin.jpademo.util.ValidateMember;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class StockService {
    @Resource
    private StockDao stockDao;

    @Resource
    private RepoInfoService repoInfoService;

    @Resource
    private GoodService goodService;

    @Resource
    private Dynamic_RepoInfoDao dynamic_repoInfoDao;


    /**
     * 查询仓库
     */
    // 返回所有仓库
    public List<StockPO> findAll() {
        List<StockPO> all = stockDao.findAll();
        return all;
    }

    // 返回指定id仓库
    public StockPO findById(Long id) {
        StockPO stockPO = stockDao.findById(id).get();
        return stockPO;
    }

    // 按库名查找
    public List<StockPO> findAllByName(String name) {
        return stockDao.findAllByName(name);
    }

    /**
     * 保存
     *
     * @param stockPO
     *
     * @return
     */
    public AjaxResult save(StockPO stockPO) {
        AjaxResult check = EntityCheckUtil.check(stockPO);
        if (check.getCode() != 200) {
            return AjaxResult.fail(500, check.getMsg());
        }
        stockPO.setCreateTime(new Date());
        StockPO save = stockDao.save(stockPO);
        if (save == null) {
            return AjaxResult.fail(500, "新建仓库信息失败");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("newStock", save);

        return AjaxResult.success(200, "新建仓库成功", map);
    }

    public AjaxResult saveModify(StockPO stockPO) {
        AjaxResult check = EntityCheckUtil.check(stockPO);
        if (check.getCode() != 200) {
            return AjaxResult.fail(500, check.getMsg());
        }
        if (ValidateMember.isEmpty(stockPO.getId())) {
            return AjaxResult.fail(500, "上传仓库信息有误");
        }

        StockPO byIdStock = findById(stockPO.getId());
        byIdStock.setAddress(stockPO.getAddress());
        byIdStock.setName(stockPO.getName());
        byIdStock.setComment(stockPO.getComment());
        byIdStock.setEmail(stockPO.getEmail());
        byIdStock.setLinkman(stockPO.getLinkman());
        byIdStock.setPhone(stockPO.getPhone());
        byIdStock.setUpdateTime(new Date());
        StockPO save = stockDao.save(byIdStock);
        if (save == null) {
            return AjaxResult.fail(500, "仓库信息保存有错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("newStock", save);

        return AjaxResult.success(200, "仓库修改成功", map);

    }

    /**
     * 修改仓储阈值
     *
     * @param list
     *
     * @return
     */
    public AjaxResult savethreshoAjax(List<RepoInfoPO> list) {
        if (list == null || list.size() <= 0) {
            return AjaxResult.success(200, "没有新阈值设定", null);
        }

        boolean flag = false;
        for (RepoInfoPO repoInfoPO : list) {
            if (repoInfoPO.getGoodPO() == null || ValidateMember.isEmpty(repoInfoPO.getGoodPO().getId())) {
                return AjaxResult.success(500, "上传商品数据有误 设定阈值失败", null);
            }

            if (repoInfoPO.getStockPO() == null || ValidateMember.isEmpty(repoInfoPO.getStockPO().getId())) {
                return AjaxResult.success(500, "上传仓库数据有误 设定阈值失败", null);
            }
        }

        for (RepoInfoPO repoInfoPO : list) {
            if (repoInfoPO.getId() != null) {
                RepoInfoPO repoInfobyId = repoInfoService.findById(repoInfoPO.getId());
                repoInfobyId.setThreshold(repoInfoPO.getThreshold());
                GoodPO goodbyId = goodService.findById(repoInfoPO.getGoodPO().getId());
                repoInfobyId.setGoodPO(goodbyId);

                StockPO stockById = stockDao.findById(repoInfoPO.getStockPO().getId()).get();
                repoInfobyId.setStockPO(stockById);

                repoInfobyId.setUpdateTime(new Date());
                repoInfoService.save(repoInfobyId);
            } else {
                RepoInfoPO newRepoInfo = new RepoInfoPO();

                newRepoInfo.setCreateTime(new Date());

                GoodPO goodbyId = goodService.findById(repoInfoPO.getGoodPO().getId());
                newRepoInfo.setGoodPO(goodbyId);

                StockPO stockById = stockDao.findById(repoInfoPO.getStockPO().getId()).get();
                newRepoInfo.setStockPO(stockById);

                repoInfoService.save(newRepoInfo);
            }

        }


        return AjaxResult.success(200, "成功修改存储阈值", null);
    }

    /**
     * 库存信息
     *
     * @param goodName
     * @param stockid
     * @param repostatus
     *
     * @return
     */
    public List<RepoInfoPO> dynamicfindAll(String goodName, Long stockid, Integer repostatus) {

        Sort byStockPO = Sort.by(Sort.Direction.ASC, "stockPO.id");
        Sort bygoodPOName = Sort.by(Sort.Direction.ASC, "goodPO.name");
        Sort andsort = byStockPO.and(bygoodPOName);

        List<RepoInfoPO> all = dynamic_repoInfoDao.findAll(new Specification<RepoInfoPO>() {
            @Override
            public Predicate toPredicate(Root<RepoInfoPO> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

                Predicate predicate = null;

                Predicate likegoodName = null;
                if (!ValidateMember.isEmpty(goodName)) {
                    Path<GoodPO> goodPONamePath = root.get("goodPO");
                    likegoodName = cb.like(goodPONamePath.get("name"), "%"+goodName+"%");

                    if (predicate == null) {
                        predicate = likegoodName;
                    } else {
                        predicate = cb.and(predicate, likegoodName);
                    }

                }

                Predicate eqstockPOid = null;
                if (!ValidateMember.isEmpty(stockid)) {
                    Path<StockPO> stockPOPath = root.get("stockPO");
                    eqstockPOid = cb.equal(stockPOPath.get("id"), stockid);

                    if (predicate == null) {
                        predicate = eqstockPOid;
                    } else {
                        predicate = cb.and(predicate, eqstockPOid);
                    }
                }

                Predicate predicatestatus = null;
                if (repostatus != null) {
                    Path<Integer> threshold = root.get("threshold");
                    Path<Integer> goodcount = root.get("goodcount");
                    Path<Integer> goodspare = root.get("goodspare");
                    if (repostatus == 1) {
                        predicatestatus = cb.lessThan(threshold, goodcount);


                    } else {
                        predicatestatus = cb.greaterThanOrEqualTo(threshold, goodcount);
                    }

                    if (predicate == null) {
                        predicate = predicatestatus;
                    } else {
                        predicate = cb.and(predicate, predicatestatus);
                    }
                }


                return predicate;
            }
        }, andsort);

        return all;
    }


    /**
     * 库存内所有商品 ,不同库存合并处理,出数量
     * sell使用
     * @return
     */
    public AjaxResult getGoodlistAjax(){
        return  null;
    }

    public List<RepoInfoPO> findAllNeedReplenish(){
        return repoInfoService.findAllNeedReplenish();
    }



}
